import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { 
  BusinessSystem, 
  BusinessStatistics, 
  CreateBusinessSystem, 
  UpdateBusinessSystem,
  AssessmentStatus,
  AssessmentType
} from '@/types/business';
import { businessApi } from '@/api/business';
import { templateApi } from '@/api/template';
import type { TemplateTable } from '@/types/template';
import { showMessage } from '@/components/common/MessageTip';

// 缓存配置
const CACHE_KEY = 'business-store';
const CACHE_VERSION = 1;
const MAX_CACHED_PLANS = 3; // 最多缓存3个计划的数据

// 初始状态
interface BusinessState {
  businessSystems: BusinessSystem[];
  statistics: BusinessStatistics;
  selectedBusiness: BusinessSystem | null;
  isLoading: boolean;
  error: Error | null;
  cachedBusinessData: Record<string, {
    businessSystems: BusinessSystem[];
    statistics: BusinessStatistics;
    lastUpdated: number;
  }>;
}

const initialState: BusinessState = {
  businessSystems: [],
  statistics: { total: 0, inProgress: 0, completed: 0 },
  selectedBusiness: null,
  isLoading: false,
  error: null,
  cachedBusinessData: {}
};

// Store 接口定义
interface BusinessStore {
  // 状态
  state: BusinessState;
  
  // 操作方法
  setSelectedBusiness: (business: BusinessSystem | null) => void;
  fetchBusinessSystems: () => Promise<void>;
  addBusinessSystem: (data: CreateBusinessSystem) => Promise<BusinessSystem>;
  updateBusinessSystem: (id: string, data: UpdateBusinessSystem) => Promise<void>;
  deleteBusinessSystem: (id: string) => Promise<void>;
  searchBusinessSystems: (keyword: string) => Promise<BusinessSystem[]>;
  filterBusinessSystems: (status?: AssessmentStatus, type?: AssessmentType) => Promise<BusinessSystem[]>;
  fetchTemplates: (assessmentType: '101' | '102' | '103'| '104') => Promise<TemplateTable[]>;
  
  // 缓存管理
  cachePlanData: (planId: string) => void;
  loadCachedPlanData: (planId: string) => boolean;
  clearCache: () => void;
}

export const useBusinessStore = create<BusinessStore>()(
  persist(
    (set, get) => ({
      state: initialState,
      
      // 设置选中的业务系统
      setSelectedBusiness: (business) => {
        set(state => ({
          state: {
            ...state.state,
            selectedBusiness: business
          }
        }));
        
        // 保存到本地存储
        if (business) {
          localStorage.setItem('selectedBusiness', JSON.stringify(business));
          showMessage('info', `已选择业务系统: ${business.name}`);
        } else {
          localStorage.removeItem('selectedBusiness');
          showMessage('info', '已清除选择的业务系统');
        }
      },
      
      // 获取所有业务系统
      fetchBusinessSystems: async () => {
        set(state => ({ 
          state: { 
            ...state.state, 
            isLoading: true, 
            error: null 
          } 
        }));
        
        try {
          const { items } = await businessApi.list();
          
          // 转换API响应为BusinessSystem格式
          const systems = items
            .map(item => {
              try {
                return businessApi.toBusinessSystem(item);
              } catch (e) {
                console.error('Error transforming business system:', e, 'Item:', item);
                return null;
              }
            })
            .filter(Boolean) as BusinessSystem[];
          
          // 更新统计数据
          let stats;
          try {
            stats = await businessApi.getStatistics();
          } catch (statsError) {
            console.error('Error fetching statistics:', statsError);
            // 回退到本地计算
            stats = {
              total: systems.length,
              inProgress: systems.filter(s => s.status === 'in_progress').length,
              completed: systems.filter(s => s.status === 'completed').length
            };
            showMessage('warning', '获取统计数据失败，已使用本地计算');
          }
          
          set(state => ({
            state: {
              ...state.state,
              businessSystems: systems,
              statistics: {
                total: stats.total || systems.length,
                inProgress: stats.inProgress || systems.filter(s => s.status === 'in_progress').length,
                completed: stats.completed || systems.filter(s => s.status === 'completed').length
              },
              isLoading: false
            }
          }));
          
        } catch (err) {
          const error = err instanceof Error 
            ? err 
            : new Error('Failed to fetch business systems');
            
          console.error('Error in fetchBusinessSystems:', error);
          
          set(state => ({
            state: {
              ...state.state,
              error,
              isLoading: false
            }
          }));
        }
      },
      
      // 添加业务系统
      addBusinessSystem: async (data: CreateBusinessSystem) => {
        set(state => ({ 
          state: { 
            ...state.state, 
            isLoading: true, 
            error: null 
          } 
        }));
        
        try {
          // 将BusinessSystem类型转换为API所需的AssessmentPlanCreate类型
          const apiData = businessApi.fromBusinessSystem(data) as {
            name: string;
            rating_filing_name: string;
            responsible_person: string;
            business_department: string;
            contact: string;
            assessment_type: '101' | '102';
            template_id: string;
            expected_completion_date: string;
          };
          // 调用API创建业务系统
          const response = await businessApi.create(apiData);
          const newSystem = businessApi.toBusinessSystem(response);
          
          // 更新状态
          set(state => ({
            state: {
              ...state.state,
              businessSystems: [...state.state.businessSystems, newSystem],
              isLoading: false
            }
          }));
          
          // 更新统计信息
          const stats = await businessApi.getStatistics();
          set(state => ({
            state: {
              ...state.state,
              statistics: {
                total: stats.total,
                inProgress: stats.inProgress,
                completed: stats.completed
              }
            }
          }));
          
          return newSystem;
        } catch (err) {
          const error = err instanceof Error 
            ? err 
            : new Error('Failed to add business system');
            
          console.error('Error adding business system:', error);
          
          set(state => ({
            state: {
              ...state.state,
              error,
              isLoading: false
            }
          }));
          
          throw error;
        }
      },
      
      // 更新业务系统
      updateBusinessSystem: async (id: string, data: UpdateBusinessSystem) => {
        set(state => ({ 
          state: { 
            ...state.state, 
            isLoading: true, 
            error: null 
          } 
        }));
        
        try {
          // 将BusinessSystem类型转换为API所需的AssessmentPlanUpdate类型
          // 更新时可以是部分字段，所以使用Partial类型
          const apiData = businessApi.fromBusinessSystem(data);
          // 调用API更新业务系统
          const response = await businessApi.update(id, apiData);
          const updatedSystem = businessApi.toBusinessSystem(response);
          
          // 更新状态
          set(state => {
            const updatedSystems = state.state.businessSystems.map(system => 
              system.id === id ? updatedSystem : system
            );
            
            // 如果更新的是当前选中的业务系统，也更新selectedBusiness
            const updatedSelectedBusiness = 
              state.state.selectedBusiness?.id === id 
                ? updatedSystem 
                : state.state.selectedBusiness;
            
            return {
              state: {
                ...state.state,
                businessSystems: updatedSystems,
                selectedBusiness: updatedSelectedBusiness,
                isLoading: false
              }
            };
          });
          
          // 如果选中的业务系统被更新了，也更新本地存储
          if (get().state.selectedBusiness?.id === id) {
            localStorage.setItem('selectedBusiness', JSON.stringify(updatedSystem));
          }
          
          showMessage('success', '业务系统更新成功');
        } catch (err) {
          const error = err instanceof Error 
            ? err 
            : new Error('Failed to update business system');
            
          console.error('Error updating business system:', error);
          
          set(state => ({
            state: {
              ...state.state,
              error,
              isLoading: false
            }
          }));
          
          showMessage('error', error instanceof Error ? error.message : '更新业务系统失败');
          throw error;
        }
      },
      
      // 删除业务系统
      deleteBusinessSystem: async (id) => {
        set(state => ({ 
          state: { 
            ...state.state, 
            isLoading: true, 
            error: null 
          } 
        }));
        
        try {
          // 调用API删除业务系统
          await businessApi.delete(id);
          
          set(state => {
            // 如果删除的是当前选中的业务系统，清除选择
            const updatedSelectedBusiness = 
              state.state.selectedBusiness?.id === id 
                ? null 
                : state.state.selectedBusiness;
            
            // 从列表中移除系统
            const updatedSystems = state.state.businessSystems.filter(
              system => system.id !== id
            );
            
            return {
              state: {
                ...state.state,
                businessSystems: updatedSystems,
                selectedBusiness: updatedSelectedBusiness,
                isLoading: false
              }
            };
          });
          
          // 如果删除的是当前选中的业务系统，也从本地存储中删除
          if (get().state.selectedBusiness?.id === id) {
            localStorage.removeItem('selectedBusiness');
          }
          
          // 更新统计信息
          const stats = await businessApi.getStatistics();
          set(state => ({
            state: {
              ...state.state,
              statistics: {
                total: stats.total,
                inProgress: stats.inProgress,
                completed: stats.completed
              }
            }
          }));
          
          showMessage('success', '业务系统删除成功');
        } catch (err) {
          const error = err instanceof Error 
            ? err 
            : new Error('Failed to delete business system');
            
          console.error('Error deleting business system:', error);
          
          set(state => ({
            state: {
              ...state.state,
              error,
              isLoading: false
            }
          }));
          
          showMessage('error', error instanceof Error ? error.message : '删除业务系统失败');
          throw error;
        }
      },
      
      // 搜索业务系统
      searchBusinessSystems: async (keyword) => {
        try {
          if (!keyword.trim()) return get().state.businessSystems;
          
          const searchTerm = keyword.toLowerCase();
          const results = get().state.businessSystems.filter(system => 
            system.name.toLowerCase().includes(searchTerm) ||
            system.responsiblePerson.toLowerCase().includes(searchTerm) ||
            system.businessDepartment.toLowerCase().includes(searchTerm) ||
            system.ratingFilingName.toLowerCase().includes(searchTerm) ||
            system.contact.toLowerCase().includes(searchTerm)
          );
          
          return results;
        } catch (error) {
          console.error('Error in searchBusinessSystems:', error);
          return [];
        }
      },
      
      // 按状态和评估类型过滤业务系统
      filterBusinessSystems: async (status, type) => {
        try {
          const results = get().state.businessSystems.filter(system => {
            const matchesStatus = !status || system.status === status;
            const matchesType = !type || system.assessmentType === type;
            return matchesStatus && matchesType;
          });
          
          return results;
        } catch (error) {
          console.error('Error in filterBusinessSystems:', error);
          return [];
        }
      },
      
      
      // 获取模板列表
      fetchTemplates: async (assessmentType) => {
        set(state => ({ 
          state: { 
            ...state.state, 
            isLoading: true, 
            error: null 
          } 
        }));
        
        try {
          const response = await templateApi.getTemplates({ 
            assessment_type: assessmentType,
            limit: 100 // 获取最多100条记录
          });
          
          set(state => ({ 
            state: { 
              ...state.state, 
              isLoading: false 
            } 
          }));
          
          return response.items || [];
        } catch (error) {
          console.error('Error fetching templates:', error);
          
          set(state => ({
            state: {
              ...state.state,
              error: error instanceof Error ? error : new Error('Failed to fetch templates'),
              isLoading: false
            }
          }));
          
          showMessage('error', '获取模板列表失败');
          return [];
        }
      },
      
      // 缓存计划数据
      cachePlanData: (planId) => {
        if (!planId) return;
        
        const { businessSystems, statistics } = get().state;
        const cachedData = {
          businessSystems,
          statistics,
          lastUpdated: Date.now()
        };
        
        set(state => {
          // 获取现有缓存
          const existingCache = { ...state.state.cachedBusinessData };
          
          // 添加新缓存
          existingCache[planId] = cachedData;
          
          // 如果缓存超过限制，删除最旧的
          const cacheKeys = Object.keys(existingCache);
          if (cacheKeys.length > MAX_CACHED_PLANS) {
            // 按最后更新时间排序
            const sortedKeys = cacheKeys.sort((a, b) => 
              existingCache[a].lastUpdated - existingCache[b].lastUpdated
            );
            
            // 删除最旧的
            delete existingCache[sortedKeys[0]];
          }
          
          return {
            state: {
              ...state.state,
              cachedBusinessData: existingCache
            }
          };
        });
        
        showMessage('info', `业务数据已缓存`);
      },
      
      // 加载缓存的计划数据
      loadCachedPlanData: (planId) => {
        if (!planId) return false;
        
        const cachedData = get().state.cachedBusinessData[planId];
        if (!cachedData) {
          showMessage('warning', '未找到缓存数据');
          return false;
        }
        
        set(state => ({
          state: {
            ...state.state,
            businessSystems: cachedData.businessSystems,
            statistics: cachedData.statistics
          }
        }));
        
        showMessage('success', '已加载缓存数据');
        return true;
      },
      
      // 清除缓存
      clearCache: () => {
        set(state => ({
          state: {
            ...state.state,
            cachedBusinessData: {}
          }
        }));
        
        showMessage('success', '缓存已清除');
      }
    }),
    {
      name: CACHE_KEY,
      version: CACHE_VERSION,
      partialize: (state) => ({ 
        state: {
          selectedBusiness: state.state.selectedBusiness,
          cachedBusinessData: state.state.cachedBusinessData
        } 
      })
    }
  )
);

// 导出便捷的Hook，保持与原有API兼容
export const useBusiness = () => {
  const store = useBusinessStore();
  
  return {
    businessSystems: store.state.businessSystems,
    statistics: store.state.statistics,
    selectedBusiness: store.state.selectedBusiness,
    isLoading: store.state.isLoading,
    error: store.state.error,
    setSelectedBusiness: store.setSelectedBusiness,
    fetchBusinessSystems: store.fetchBusinessSystems,
    addBusinessSystem: store.addBusinessSystem,
    updateBusinessSystem: store.updateBusinessSystem,
    deleteBusinessSystem: store.deleteBusinessSystem,
    searchBusinessSystems: store.searchBusinessSystems,
    filterBusinessSystems: store.filterBusinessSystems,
    fetchTemplates: store.fetchTemplates,
    // 新增的缓存方法
    cachePlanData: store.cachePlanData,
    loadCachedPlanData: store.loadCachedPlanData,
    clearCache: store.clearCache
  };
};
